import { ref } from 'vue'
import { defineStore } from 'pinia'
import { getToken, setToken, removeToken } from '@/utils/token'
import { login, logout, getInfo } from '@/http/login'
import { resetRouter } from '@/router/index'

const clientSetting = {
  grant_type: 'password',
  scope: '',
  username: '',
  password: '',
  client_id: import.meta.env.VITE_CLIENT_ID,
  client_secret: import.meta.env.VITE_CLIENT_PASSWORD,
}

// 使用setup模式定义
export const userStore = defineStore('userStore', () => {
  const token = ref(getToken())
  const name = ref('')
  const userName = ref('')
  const surname = ref('')
  const avatar = ref(
    'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
  )
  const email = ref('')
  const introduction = ref('')
  const phoneNumber = ref('')
  const roles = ref<any[]>([])

  function SET_TOKEN(value: string) {
    token.value = value
  }
  function SET_INTRODUCTION(value: string) {
    introduction.value = value
  }
  function SET_NAME(value: string) {
    name.value = value
  }
  function SET_USERNAME(value: string) {
    userName.value = value
  }
  function SET_TEL(value: string) {
    phoneNumber.value = value
  }
  function SET_AVATAR(value: string) {
    const url =
      'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
    avatar.value = value || url
  }
  // function SET_ROLES (value:any[]) {
  //   roles.value = value
  // }
  function SET_EMAIL(value: string) {
    email.value = value
  }
  function SET_SURNAME(value: string) {
    surname.value = value
  }
  function CLEAN() {
    token.value = ''
    name.value = ''
    userName.value = ''
    avatar.value = ''
    email.value = ''
    introduction.value = ''
    phoneNumber.value = ''
    roles.value = []
    surname.value = ''
  }
  function handleLogin(userInfo: any) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      clientSetting.username = username.trim()
      clientSetting.password = password
      login(clientSetting)
        .then((response) => {
          SET_TOKEN(response.access_token)
          setToken(response.access_token)
          resolve(true)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  function handleLogout() {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          removeToken() // must remove  token  first
          resetRouter()
          CLEAN()
          resolve(true)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  // get user info
  function handleGetInfo() {
    return new Promise((resolve, reject) => {
      getInfo()
        .then((response: any) => {
          if (!response) {
            reject(new Error('验证失败, 请重新登录.'))
          }
          const {
            userName,
            name,
            surname,
            phoneNumber,
            email,
            extraProperties,
          } = response
          SET_NAME(name)
          SET_SURNAME(surname)
          SET_USERNAME(userName)
          SET_TEL(phoneNumber)
          SET_AVATAR(extraProperties.Avatar)
          SET_EMAIL(email)
          SET_INTRODUCTION(extraProperties.Introduction)
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  function resetToken() {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      CLEAN()
      resolve(true)
    })
  }
  return {
    userName,
    name,
    handleLogin,
    handleLogout,
    handleGetInfo,
    resetToken,
    token,
  }
})
// import { Module } from 'vuex'
// import { RootState } from '../index'
// import { login, logout, getInfo } from '@/http/login'
// import { getToken, setToken, removeToken } from '@/utils/token'
// import { resetRouter } from '@/router/index'
//
// const clientSetting = {
//   grant_type: 'password',
//   scope: '',
//   username: '',
//   password: '',
//   client_id: 'SealLabel_App',
//   client_secret: '1q2w3e*'
// }
//
// export interface UserState {
//   token:string,
//   name: string,
//   userName: string,
//   surname: string,
//   avatar: string,
//   email: string,
//   introduction: string,
//   phoneNumber: string,
//   roles: any[]
// }
//
// export const store: Module<UserState, RootState> = {
//   namespaced: true,
//   state: (): UserState => ({
//     token: getToken(),
//     name: '',
//     userName: '',
//     surname: '',
//     avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
//     email: '',
//     introduction: '',
//     phoneNumber: '',
//     roles: []
//   }),
//   mutations: {
//     SET_TOKEN: (state, token) => {
//       state.token = token
//     },
//     SET_INTRODUCTION: (state, introduction) => {
//       state.introduction = introduction
//     },
//     SET_NAME: (state, name) => {
//       state.name = name
//     },
//     SET_USERNAME: (state, userName) => {
//       state.userName = userName
//     },
//     SET_TEL: (state, phoneNumber) => {
//       state.phoneNumber = phoneNumber
//     },
//     SET_AVATAR: (state, avatar) => {
//       const url =
//         'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
//       state.avatar = avatar || url
//     },
//     SET_ROLES: (state, roles) => {
//       state.roles = roles
//     },
//     SET_EMAIL: (state, email) => {
//       state.email = email
//     },
//     SET_SURNAME: (state, surname) => {
//       state.surname = surname
//     },
//     CLEAN: state => {
//       state.token = ''
//       state.name = ''
//       state.userName = ''
//       state.avatar = ''
//       state.email = ''
//       state.introduction = ''
//       state.phoneNumber = ''
//       state.roles = []
//       state.surname = ''
//     }
//   },
//   actions: {
//     login ({ commit }, userInfo) {
//       const { username, password } = userInfo
//       return new Promise((resolve, reject) => {
//         clientSetting.username = username.trim()
//         clientSetting.password = password
//         login(clientSetting)
//           .then((response) => {
//             commit('SET_TOKEN', response.access_token)
//             setToken(response.access_token)
//             resolve(true)
//           })
//           .catch(error => {
//             reject(error)
//           })
//       })
//     },
//     logout ({ commit, state }) {
//       return new Promise((resolve, reject) => {
//         logout()
//           .then(() => {
//             removeToken() // must remove  token  first
//             resetRouter()
//             commit('CLEAN')
//             resolve(true)
//           })
//           .catch(error => {
//             reject(error)
//           })
//       })
//     },
//     // get user info
//     getInfo ({ commit, state }) {
//       return new Promise((resolve, reject) => {
//         getInfo()
//           .then((response:any) => {
//             if (!response) {
//               reject(new Error('验证失败, 请重新登录.'))
//             }
//             const {
//               userName,
//               name,
//               surname,
//               phoneNumber,
//               email,
//               extraProperties
//             } = response
//             commit('SET_NAME', name)
//             commit('SET_SURNAME', surname)
//             commit('SET_USERNAME', userName)
//             commit('SET_TEL', phoneNumber)
//             commit('SET_AVATAR', extraProperties.Avatar)
//             commit('SET_EMAIL', email)
//             commit('SET_INTRODUCTION', extraProperties.Introduction)
//             resolve(response)
//           })
//           .catch(error => {
//             reject(error)
//           })
//       })
//     },
//     resetToken ({ commit }) {
//       return new Promise(resolve => {
//         removeToken() // must remove  token  first
//         commit('CLEAN')
//         resolve(true)
//       })
//     }
//   }
// }
